import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import { Card, Form, Input, Button, DatePicker, InputNumber, message, Space } from 'antd';
import { StarOutlined } from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import moment from 'moment';
import axios from 'axios';

function FundDetail() {
  const { code } = useParams();
  const [fund, setFund] = useState(null);
  const [netValues, setNetValues] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetchFundDetail();
    fetchNetValues();
  }, [code]);

  const fetchFundDetail = async () => {
    try {
      const response = await axios.get(`http://localhost:5000/api/fund/${code}`);
      setFund(response.data);
    } catch (error) {
      message.error('获取基金详情失败');
    }
  };

  const fetchNetValues = async () => {
    try {
      const endDate = moment().format('YYYY-MM-DD');
      const startDate = moment().subtract(30, 'days').format('YYYY-MM-DD');
      const response = await axios.get(
        `http://localhost:5000/api/fund/${code}/net_values?start_date=${startDate}&end_date=${endDate}`
      );
      setNetValues(response.data);
    } catch (error) {
      message.error('获取净值数据失败');
    }
  };

  const onAddToMyFunds = async (values) => {
    try {
      setLoading(true);
      await axios.post('http://localhost:5000/api/user/fund', {
        fund_code: code,
        buy_date: values.buy_date.format('YYYY-MM-DD'),
        expected_rate: values.expected_rate,
      });
      message.success('添加成功');
    } catch (error) {
      message.error('添加失败');
    } finally {
      setLoading(false);
    }
  };

  const getChartOption = () => {
    const dates = netValues.map(item => item.date);
    const unitValues = netValues.map(item => item.unit_value);
    const totalValues = netValues.map(item => item.total_value);

    return {
      title: {
        text: '净值走势图'
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['单位净值', '累计净值']
      },
      xAxis: {
        type: 'category',
        data: dates
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '单位净值',
          type: 'line',
          data: unitValues
        },
        {
          name: '累计净值',
          type: 'line',
          data: totalValues
        }
      ]
    };
  };

  if (!fund) {
    return null;
  }

  return (
    <div>
      <Card title={`${fund.name} (${fund.code})`}>
        <Space direction="vertical" size="large" style={{ width: '100%' }}>
          <ReactECharts option={getChartOption()} style={{ height: 400 }} />
          
          <Card title="添加到自选">
            <Form onFinish={onAddToMyFunds}>
              <Form.Item
                name="buy_date"
                label="购买日期"
                rules={[{ required: true, message: '请选择购买日期' }]}
              >
                <DatePicker />
              </Form.Item>
              
              <Form.Item
                name="expected_rate"
                label="预期收益率(%)"
                rules={[{ required: true, message: '请输入预期收益率' }]}
              >
                <InputNumber min={0} max={100} />
              </Form.Item>
              
              <Form.Item>
                <Button type="primary" htmlType="submit" icon={<StarOutlined />} loading={loading}>
                  加入自选
                </Button>
              </Form.Item>
            </Form>
          </Card>
        </Space>
      </Card>
    </div>
  );
}

export default FundDetail; 